<template>
  <div class="permission-container">
    <div class="app-container">
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="showDialog({ type: 1, pid: '0' })">添加权限</el-button>
        </div>
        <!-- 表格 -->
        <!-- 
          渲染树形结构的表格需要满足的条件
          1. 将数据转换为树形数据
          2. 为 el-table 添加 row-key="id" 唯一标识，id 就是数据中的 id
        -->
        <el-table :data="list" border row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" @click="showDialog({ type: 2, pid: row.id })">添加</el-button>
              <el-button type="text" @click="showDialogEdit(row.id)">编辑</el-button>
              <el-button type="text" @click="deletePermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <!-- 添加/编辑权限点弹窗 -->
    <permission-dialog 
      ref="PermissionDialog"
      :dialogVisible="dialogVisible"
      @close-dialog="closeDialog"
      :type="type"
      :pid="pid"
      @get-permission-list="getPermissionList">
    </permission-dialog>
  </div>
</template>

<script>
import { getPermissionList, deletePermission } from '@/api/permission'
import { transTree } from '@/utils/transTree'
import PermissionDialog from './componets/permission-dialog.vue'

export default {
  components: {
    PermissionDialog
  },
  data() {
    return {
      // 权限点列表数据
      list: [],
      // 控制弹窗显示与隐藏的数据
      dialogVisible: false,
      type: '',
      pid: ''
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取权限点列表数据
    async getPermissionList() {
      const res = await getPermissionList()
      // console.log(res);
      this.list = transTree(res.data)
    },
    // 点击添加按钮，打开弹窗
    showDialog({ type, pid }) {
      // console.log('type', type);
      // console.log('pid', pid);
      this.type = type
      this.pid = pid
      this.dialogVisible = true
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false
    },
    // 点击编辑按钮，打开弹窗
    showDialogEdit(id) {
      // 打开弹窗
      this.dialogVisible = true
      // 调用弹窗子组件中获取权限点详细数据的方法，完成数据回显
      this.$refs.PermissionDialog.getPermissionDetail(id)
    },
    // 点击删除
    deletePermission(id) {
      // 1. 询问用户
      this.$confirm('此操作将永久删除该权限点, 是否继续?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(async () => {
        // 2. 调用删除接口
        await deletePermission(id)
        // 3. 提示用户
        this.$message.success('删除权限点成功')
        // 4. 刷新表格数据
        this.getPermissionList()
      })
    }
  }
}
</script>
